package com.mnt.washio.utils.network.ws;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;

import com.mnt.washio.objects.Address;
import com.mnt.washio.utils.Statics;
import com.mnt.washio.utils.network.NetworkUtils;
import com.mnt.washio.utils.network.WebServiceCommunicatorListener;

@SuppressLint("SimpleDateFormat")
public class GetAddressListWSControl extends BaseWSControl {
	private String userId;

	public GetAddressListWSControl(Context context,
			WebServiceCommunicatorListener listener, String userId) {
		super(context, listener, WebServiceFlag.GET_ADDRESS);
		this.userId = userId;

	}

	@Override
	protected Object doInBackground(Void... params) {
		// Get local database

		String url = Statics.ADMIN_WS_URL + "account/address/" + userId;
		LinkedHashMap<String, String> headers = new LinkedHashMap<String, String>();

		try {
			String respone = NetworkUtils.doRequest(url, headers);
			try {
				JSONArray jsonArray = new JSONArray(respone);
				return getAddressFromJSONObject(jsonArray);

			} catch (JSONException e) {
				mError = e.getMessage();
			}

		} catch (ClientProtocolException e) {
			mError = "Cannot connect to network";
			e.printStackTrace();
		} catch (IOException e) {
			mError = "Cannot connect to network";
			e.printStackTrace();
		}
		return null;
	}

	public ArrayList<Address> getAddressFromJSONObject(
			JSONArray addressJsonArray) throws JSONException {
		ArrayList<Address> arrayAddress = new ArrayList<Address>();
		Address address;
		for (int i = 0; i < addressJsonArray.length(); i++) {
			JSONObject json = addressJsonArray.getJSONObject(i);
			address = new Address();
			address.setObjectId(json.getString("objectId"));
			address.setAddress(json.getString("address"));
			address.setName(json.getString("name"));
			address.setNote(json.getString("note"));
			address.setZipCode(json.getString("zip"));

			if (json.has("state")) {
				address.setState(json.getString("state"));
			}
			if (json.has("is_active")) {
				address.setActive(json.getBoolean("is_active"));
			}
			if (json.has("apartmentNumber")) {
				address.setApartmentNumber(json.getString("apartmentNumber"));
			}
			if (json.has("city")) {
				address.setCity(json.getString("city"));
			}
			if (json.has("latitude")) {
				address.setLatitude(json.getDouble("latitude"));
			}
			if (json.has("longitude")) {
				address.setLongitude(json.getDouble("longitude"));
			}
			if (json.has("timezone")) {
				address.setTimeZone(json.getString("timezone"));
			}

			arrayAddress.add(address);

		}
		return arrayAddress;
	}
}
